/*

Summary:
A wrapper for heap buffer, can free the memory automatically.

Remark:
None.

Version:
0.1.0

LastUpdatedDate:
2012-10-04

*/

#pragma once


namespace Zaf {


template<typename Element>
class Buffer {

public:
	explicit Buffer(unsigned int length) {
		Ctor(length);
	}

	Buffer(unsigned int length, Element element) {
		Ctor(length);
		Fill(element);
	}

	~Buffer() { delete [] m_buffer; }

	void Resize(unsigned int length) {
		DoResize(length);
	}

	void Resize(unsigned int length, Element element) {
		DoResize(length);
		Fill(element);
	}

	Element* Get() { return m_buffer; }
	const Element* Get() const { return m_buffer; }

	operator Element*() { return m_buffer; }
	operator const Element*() const { return m_buffer; }

	Element& operator[](int index) { return m_buffer[(unsigned int)index]; }
	const Element& operator[](int index) const { return m_buffer[(unsigned int)index]; }

	unsigned int GetLength() const { return m_length; }

	void Fill(Element element) {
		Element* pElement = m_buffer;
		while (pElement - m_buffer < m_length) {
			*pElement = element;
		}
	}

private:
	Buffer(const Buffer&);
	const Buffer& operator=(const Buffer&);

	void Ctor(unsigned int length) {
		m_buffer = new Element[length];
		m_length = length;
	}

	void DoResize(unsigned int length) {
		delete [] m_buffer;
		m_buffer = new Element[length];
		m_length = length;
	}

	Element* m_buffer;
	unsigned int m_length;
};

}